package dom;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class TestDOMParserPrint {

    public static void main(String[] args) {
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder parser=factory.newDocumentBuilder();

            Document document= parser.parse(TestDOMParserPrint.class
                                                              .getClassLoader()
                                                              .getResourceAsStream("students.xml"));

            Element root=document.getDocumentElement();

            print(root);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void print(Element root){
        System.out.print("<"+root.getTagName()+" ");

        NamedNodeMap map=root.getAttributes();
        
        if(map!=null){
            for (int i = 0; i < map.getLength(); i++) {
                Attr attr= (Attr) map.item(i);
                System.out.print(attr.getName()+"=\""+attr.getValue()+"\" ");
            }
        }
        System.out.print(">");

        NodeList nodeList=root.getChildNodes();

        if(nodeList!=null){

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node=nodeList.item(i);
                short nodeType=node.getNodeType();

                if(nodeType==Node.TEXT_NODE){
                    System.out.print(node.getNodeValue());
                }
                if(nodeType==Node.ELEMENT_NODE){
                    Element element= (Element) node;
                    print(element);
                }
            }

        }



        System.out.print("</"+root.getTagName()+">");
    }

}
